package com.stlm2.dems.sns.service;

import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;
import com.stlm2.dems.dao.ConfigDao;
import com.stlm2.dems.entity.Config;
import com.stlm2.dems.sns.dao.SmsDao;
import com.stlm2.dems.sns.entity.Platform;
import com.stlm2.dems.sns.entity.Sms;
import com.stlm2.dems.sns.entity.SmsState;
import com.stlm2.dems.entity.TiXianState;
import com.stlm2.dems.dao.UserDao;
import com.stlm2.dems.entity.User;
import net.spy.memcached.MemcachedClient;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

@Service("smsService")
@Transactional(rollbackForClassName = {"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class SmsService extends BaseServiceImpl<Sms> {

    @Resource
    private SmsDao smsDao;

    @Resource
    private UserDao userDao;
    @Resource
    private ConfigDao configDao;

    @Override
    protected BaseDao<Sms> getDao() {
        return smsDao;
    }

    /**
     * 当天已经使用的短信量
     *
     * @param mobile
     * @return
     */
    public int hasSendedCount(Platform platform, String mobile) {
        if (StringUtils.isBlank(mobile))
            return Sms.dayCounts;
        long current = System.currentTimeMillis();//当前时间毫秒数
        long zero = current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();//今天零点零分零秒的毫秒数
        Date endTime = new Timestamp(current);//当前时间
        Date startTime = new Timestamp(zero);
        Sms sms = new Sms();
        sms.setMobile(mobile);
        sms.setStartTime(startTime);
        sms.setEndTime(endTime);
        List<Sms> list = smsDao.queryList(-1, -1, sms);
        if (list != null)
            return list.size();

        return 0;
    }

    /**
     * 当天的短信是否已经用完
     *
     * @param platform
     * @param mobile
     * @return
     */
    public boolean isUsedUp(Platform platform, String mobile) {
        if (StringUtils.isBlank(mobile))
            return true;

        //如果每天发送量为空则从数据库获取
        if (Sms.dayCounts == 0) {
            Sms.dayCounts = NumberUtils.toInt("20", 20);
        }

        return hasSendedCount(platform, mobile) >= 20;

    }

    /**
     * 发送短信验证码
     *
     * @param platform
     * @param user
     * @param mobile
     * @param code
     * @return
     */
    public String sendCode(Platform platform, User user, String mobile, String code) {
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(code))
            return "请提供手机号和验证码";

        if (isUsedUp(platform, mobile))
            return "您一天内只能发送" + 20 + "次验证码！";

        Sms param = getLastSms(platform, mobile);
        String result=null;
        if(isOpenSMS()){
            result = com.stlm2.core.yun.Sms.send(mobile, code);
        }else {
            result = com.stlm2.core.yun.Sms.send(adminPhone(), code);
        }

        if (result == null)
            return "短信发送失败，请重试！";
        else {
            Sms sms = new Sms();
            sms.setPlatform(platform);
            sms.setCode(code);
            sms.setSendTime(new Date());
            sms.setSid(result);
            sms.setMobile(mobile);
            sms.setSmsState(SmsState.Sended);
            addEntity(sms);

            setCodeExpired(mobile, code);
            return "success";
        }
    }

    /**
     * 发送邮箱验证码
     * @param platform
     * @param user
     * @param mobile
     * @param code
     * @return
     */
/*	public String sendEmailCode(Platform platform, User user, String mobile, String code){
        if(StringUtils.isBlank(mobile) || StringUtils.isBlank(code))
			return "请提供邮箱和验证码";
		  Thread.currentThread().setContextClassLoader( getClass().getClassLoader() );
			String result=EmailUtil.sendHtmlMail(mobile,"董事惠商城","您的验证码是："+code);

			Sms sms = new Sms();
			sms.setPlatform(platform);
			sms.setCode(code);
			sms.setSendTime(new Date());
			sms.setSid(result);
			sms.setMobile(mobile);
			sms.setSmsState(SmsState.Sended);
			addEntity(sms);

			setCodeExpired(mobile, code);
			return Constants.SUCCESS;

	}*/

    /**
     * 发送审核通知
     *
     * @param platform
     * @param user
     * @param mobile
     * @param orderCode
     * @param tiXianState
     * @return
     */
    public String sendNotice(Platform platform, User user, String mobile, String orderCode, TiXianState tiXianState) {
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(orderCode) || tiXianState==null )
            return "发送提现通知失败";

        String result=null;
        if(isOpenSMS()){
            result =  com.stlm2.core.yun.Sms.sendNotice(mobile, orderCode,tiXianState);
        }else {
            result =  com.stlm2.core.yun.Sms.sendNotice(adminPhone(), orderCode,tiXianState);
        }
        if (result == null)
            return "发送提现通知失败";
        else {
            Sms sms = new Sms();
            sms.setPlatform(platform);
            sms.setCode(orderCode);
            sms.setUserId(user.getId());
            sms.setSendTime(new Date());
            sms.setSid(result);
            sms.setMobile(mobile);
            sms.setSmsState(SmsState.Used);
            addEntity(sms);

            return "success";
        }
    }


    /**
     * 发送运营部通知
     */
    public String sendNoticeYYB(String mobile, String text) {
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(text))
            return "发送发货通知失败";
        String result=null;
        if(isOpenSMS()){
            result=com.stlm2.core.yun.Sms.sendNoticeYYB(mobile, text);
        }else {
            result= com.stlm2.core.yun.Sms.sendNoticeYYB(adminPhone(), text);
        }

//		String result = "1234450435034532534";
        if (result == null)
            return "发送发货通知失败";
        else {
            Sms sms = new Sms();
            sms.setPlatform(Platform.Web);
            sms.setCode(text);
            sms.setSendTime(new Date());
            sms.setSid(result);
            sms.setMobile(mobile);
            sms.setSmsState(SmsState.Sended);
            addEntity(sms);

            return "success";
        }
    }

    public String sendNotice(String mobile, String text[]) {
        if (StringUtils.isBlank(mobile) || text.length<=0)
            return "发送卡券通知失败";


        String result = null;
        if(isOpenSMS()){
            result=com.stlm2.core.yun.Sms.sendNotice("206105",mobile, text);
        }else {
            result= com.stlm2.core.yun.Sms.sendNotice("206105",adminPhone(), text);
        }

//		String result = "1234450435034532534";
        if (result == null)
            return "发送卡券通知失败";
        else {
            Sms sms = new Sms();
            sms.setPlatform(Platform.Web);
            sms.setCode("满减活动-"+text[0]);
            sms.setSendTime(new Date());
            sms.setSid(result);
            sms.setMobile(mobile);
            sms.setSmsState(SmsState.Sended);
            addEntity(sms);

            return "success";
        }
    }


    /**
     * 设置已发送验证码为无效
     *
     * @param mobile
     */
    private void setCodeExpired(String mobile, String exclude) {
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(exclude))
            return;

        Sms param = new Sms();
        param.setMobile(mobile);
        param.setSmsState(SmsState.Sended);
        List<Sms> list = getList(-1, -1, param);
        if (list != null && list.size() > 0) {
            for (Sms sms : list) {
                if (exclude.equals(sms.getCode()))
                    continue;

                sms.setSmsState(SmsState.Expired);
                updateEntity(sms);
            }
        }
    }

    /**
     * 获得上一条短信
     *
     * @param platform
     * @param mobile
     * @return
     */
    public Sms getLastSms(Platform platform, String mobile) {
        if (StringUtils.isBlank(mobile))
            return null;

        Sms param = new Sms();
        param.setMobile(mobile);
        if (platform != null)
            param.setPlatform(platform);
        List<Sms> list = smsDao.queryList(1, 1, param);

        if (list != null && list.size() > 0)
            return list.get(0);

        return null;
    }

    /**
     * 验证短信验证码
     *
     * @param platform
     * @param mobile
     * @param code
     * @return
     */
    public String checkCode(Platform platform, String mobile, String code, MemcachedClient memcachedClient) {
        int count = 0;
        try {
            count = Integer.valueOf(memcachedClient.get(mobile).toString());
        } catch (Exception e) {
            //System.out.println("错误验证码："+e.toString());
            memcachedClient.set(mobile, 600, 0);
        }
        if (count > 10) {
            return "您验证码验证错误次数太多，请10分钟之后再操作";
        }
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(code))
            return "请提供手机号和验证码";

        Sms sms = getLastSms(platform, mobile);
        if (sms == null)
            return "验证码错误";
		else if(!SmsState.Sended.equals(sms.getSmsState()))
			return "验证码已使用";
        else if (new Date().getTime() - sms.getSendTime().getTime() >= 30 * 60 * 1000) {
            sms.setSmsState(SmsState.Expired);
            updateEntity(sms);
            return "验证码已过期";
        } else if (!code.equals(sms.getCode())) {
            count++;
            memcachedClient.set(mobile, 600, count);
            return "验证码错误";
        } else {
            sms.setSmsState(SmsState.Used);
            sms.setUseTime(new Date());
            updateEntity(sms);

            return "success";
        }
    }

    /*
    * 手机版同时验证新旧两个验证码，为了实现只有两个验证码同时通过才设置状态为使用
    * */
    public String checkCode2(Platform platform, String mobile, String code, MemcachedClient memcachedClient) {

        int count = 0;
        try {
            count = Integer.valueOf(memcachedClient.get(mobile).toString());
        } catch (Exception e) {
            memcachedClient.set(mobile, 600, 0);
        }
        if (count > 9) {
            return "您验证码验证错误次数太多，请10分钟之后再操作";
        }
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(code)) {
            return "请提供旧手机号和验证码";
        }
        Sms sms = getLastSms(platform, mobile);
        if (sms == null) {
            return "验证码错误";
        } else if (new Date().getTime() - sms.getSendTime().getTime() >= 30 * 60 * 1000) {
            sms.setSmsState(SmsState.Expired);
            updateEntity(sms);
            return "验证码已过期";
        } else if (!code.equals(sms.getCode())) {
            count++;
            memcachedClient.set(mobile, 600, count);
            return "验证码错误";
        } else {
            sms.setUseTime(new Date());
            updateEntity(sms);
            return "success";
        }
    }
   //检验新手机号，检验通过 更换用户手机号  ffl
    public String checkCodeTwice(Platform platform, String mobile, String code,String old_mobile,User user,String token){
        if(StringUtils.isBlank(mobile) || StringUtils.isBlank(code))
            return "请提供验证码新手机号";
        if(mobile.equals(old_mobile)){
            return "新旧号码不能相同";
        }
        Sms sms = getLastSms(platform, mobile);
        if(sms == null)
            return "验证码错误";
        else if(new Date().getTime() - sms.getSendTime().getTime() >= 30 * 60 * 1000){
            sms.setSmsState(SmsState.Expired);
            updateEntity(sms);
            return "验证码已过期";
        }else if(!code.equals(sms.getCode()))
            return "验证码错误";
        Sms smsOld = getLastSms(platform, old_mobile);
        if (!SmsState.Used.equals(smsOld.getSmsState())){
            return "旧手机未验证";
        }
        if (new Date().getTime() - smsOld.getUseTime().getTime() >= 10 * 60 * 1000){
            return "旧手机验证过久，请重新验证";
        }
        if (userDao.getByName(mobile)!=null){
            return "新手机号码已被使用，不能更改为新手机号码";
        }
            sms.setSmsState(SmsState.Used);
            sms.setUseTime(new Date());
            updateEntity(sms);
            user.setName(mobile);
            userDao.updateUserToken(user,token);
            return "success";

    }
    public Sms getUserSms(String typeKey, String mobile, String platform, String email) {
        Sms sms = new Sms();
        if ("1".equals(typeKey)) {
            sms = getLastSms(Platform.Web, mobile);
            if ("ios".equals(platform)) {
                sms = getLastSms(Platform.Ios, mobile);
            } else if ("android".equals(platform)) {
                sms = getLastSms(Platform.Android, mobile);
            } else if ("wap".equals(platform)) {
                sms = getLastSms(Platform.Wap, mobile);
            } else if ("web".equals(platform)) {
                sms = getLastSms(Platform.Web, mobile);
            }
        } else if ("2".equals(typeKey)) {
            sms = getLastSms(Platform.Web, email);
            if ("ios".equals(platform)) {
                sms = getLastSms(Platform.Ios, email);
            } else if ("android".equals(platform)) {
                sms = getLastSms(Platform.Android, email);
            } else if ("wap".equals(platform)) {
                sms = getLastSms(Platform.Wap, email);
            } else if ("web".equals(platform)) {
                sms = getLastSms(Platform.Web, email);
            }
        }
        return sms;
    }

    /*
    更新验证码的使用状态
     */
    public void updateSms(Sms sms, SmsState smsState, Date date) {
        if (sms != null) {
            sms.setSmsState(smsState);
            sms.setUseTime(date);
            updateEntity(sms);
        }
    }

    /*
    *zlq
    * 获取config短信开关
    *
     */
    private  boolean isOpenSMS(){
        Config config=new Config();
        config.setConfigName("OPEN_SMS");
        config=configDao.selectOneFromRedis(config);
        if(config==null){
            config= configDao.getByName("OPEN_SMS");
        }
        if(config!=null){
            if(config.getConfigValue().equals("1")){
                return true;
            }
        }
       return false;
    }
    /*
    * zlq
     * 指定管理员手机号接收短信
     */
    private  String adminPhone(){
        return "13353613565";
    }


    /**
     * Author：fuchunyu
     * Date：2017/9/29
     * Description：订单通知
     */

    public String sendOrderNotice(String mobile, String text[]) {
        if (StringUtils.isBlank(mobile) || text.length<=0)
            return "发送订单通知失败";

        String result = null;
        if(isOpenSMS()){
            result=com.stlm2.core.yun.Sms.sendNotice("208680",mobile, text);
        }else {
            result= com.stlm2.core.yun.Sms.sendNotice("208680",adminPhone(), text);
        }
        if (result == null)
            return "发送订单通知失败";
        else {
            Sms sms = new Sms();
            sms.setPlatform(Platform.Web);
            sms.setCode(text[0]);
            sms.setSendTime(new Date());
            sms.setSid(result);
            sms.setMobile(mobile);
            sms.setSmsState(SmsState.Sended);
            addEntity(sms);
            return "success";
        }
    }

}